<i18n locale="en" lang="yaml">
requirementsTip: '"package" or "package==1.2.3", one per row'
</i18n>
<i18n locale="zh-CN" lang="yaml">
requirementsTip: '"package" 或 "package==1.2.3" 格式，每行一个'

Add Script Set  : 添加脚本集
Setup Script Set: 配置脚本集

Requirements: 依赖包

Script Set ID will be a part of the Func ID: 脚本集 ID 将作为函数 ID 的一部分
Go to PIP tool to install                  : 前往 PIP 工具安装

Please input ID                                   : 请输入 ID
Only alphabets, numbers and underscore are allowed: 只能包含大小写英文、数字及下划线
Cannot not starts with a number                   : 不得以数字开头

'ID cannot contains double underscore "__"': '不能包含双下划线 "__"'

Script Set created : 脚本集已创建
Script Set saved   : 脚本集已保存
Script Set deleted : 脚本集已删除

Are you sure you want to delete the Script Set?: 是否确认删除此脚本集？

This Script Set is locked by you: 当前脚本集已被您锁定
This Script Set is locked by other user ({user}): 当前脚本集已被其他用户（{user}）锁定
</i18n>

<!-- Generated by OpenCC START -->
<i18n locale="zh-HK" lang="yaml">
Add Script Set: 添加腳本集
Are you sure you want to delete the Script Set?: 是否確認刪除此腳本集？
Cannot not starts with a number: 不得以數字開頭
Go to PIP tool to install: 前往 PIP 工具安裝
ID cannot contains double underscore "__": 不能包含雙下劃線 "__"
Only alphabets, numbers and underscore are allowed: 只能包含大小寫英文、數字及下劃線
Please input ID: 請輸入 ID
Requirements: 依賴包
Script Set ID will be a part of the Func ID: 腳本集 ID 將作為函數 ID 的一部分
Script Set created: 腳本集已創建
Script Set deleted: 腳本集已刪除
Script Set saved: 腳本集已保存
Setup Script Set: 配置腳本集
This Script Set is locked by other user ({user}): 當前腳本集已被其他用户（{user}）鎖定
This Script Set is locked by you: 當前腳本集已被您鎖定
requirementsTip: '"package" 或 "package==1.2.3" 格式，每行一個'
</i18n>
<i18n locale="zh-TW" lang="yaml">
Add Script Set: 新增指令碼集
Are you sure you want to delete the Script Set?: 是否確認刪除此指令碼集？
Cannot not starts with a number: 不得以數字開頭
Go to PIP tool to install: 前往 PIP 工具安裝
ID cannot contains double underscore "__": 不能包含雙下劃線 "__"
Only alphabets, numbers and underscore are allowed: 只能包含大小寫英文、數字及下劃線
Please input ID: 請輸入 ID
Requirements: 依賴包
Script Set ID will be a part of the Func ID: 指令碼集 ID 將作為函式 ID 的一部分
Script Set created: 指令碼集已建立
Script Set deleted: 指令碼集已刪除
Script Set saved: 指令碼集已儲存
Setup Script Set: 配置指令碼集
This Script Set is locked by other user ({user}): 當前指令碼集已被其他使用者（{user}）鎖定
This Script Set is locked by you: 當前指令碼集已被您鎖定
requirementsTip: '"package" 或 "package==1.2.3" 格式，每行一個'
</i18n>
<!-- Generated by OpenCC END -->

<template>
  <el-dialog
    id="ScriptSetSetup"
    :visible.sync="show"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="750px">

    <template slot="title">
      {{ pageTitle }} <code class="text-main" v-if="pageMode === 'setup'">{{ data.title || data.id }}</code>
    </template>

    <el-container direction="vertical">
      <el-main>
        <div class="setup-form">
          <el-form ref="form" label-width="135px" :model="form" :disabled="!canSetup" :rules="formRules">
            <el-form-item v-if="isLockedByMe">
              <InfoBlock type="success" :title="$t('This Script Set is locked by you')" />
            </el-form-item>
            <el-form-item v-else-if="isLockedByOther">
              <InfoBlock :type="canSetup ? 'warning' : 'error'" :title="$t('This Script Set is locked by other user ({user})', { user: lockedByUser })" />
            </el-form-item>

            <el-form-item label="ID" prop="id">
              <el-input :disabled="pageMode === 'setup'"
                maxlength="60"
                v-model="form.id"></el-input>
              <InfoBlock :title="$t('Script Set ID will be a part of the Func ID')" />
            </el-form-item>

            <el-form-item :label="$t('Title')">
              <el-input :placeholder="$t('Optional')"
                maxlength="200"
                v-model="form.title"></el-input>
            </el-form-item>

            <el-form-item :label="$t('Description')">
              <el-input :placeholder="$t('Optional')"
                type="textarea"
                resize="none"
                :autosize="{minRows: 2}"
                maxlength="5000"
                v-model="form.description"></el-input>
            </el-form-item>

            <el-form-item :label="$t('Requirements')">
              <el-input :placeholder="$t('Optional')"
                type="textarea"
                resize="none"
                :autosize="{minRows: 2}"
                maxlength="5000"
                v-model="form.requirements"></el-input>
              <InfoBlock :title="$t('requirementsTip')" />
              <div class="float-right">
                <el-button v-if="requirementsLine" type="text" @click="common.goToPIPTools(requirementsLine)">{{ $t('Go to PIP tool to install') }}</el-button>
              </div>
            </el-form-item>

            <el-form-item class="setup-footer">
              <el-link type="danger" class="float-left" v-if="pageMode === 'setup'" @click="deleteData">{{ $t('Delete') }}</el-link>
              <el-button type="text" @click="showLockConfig">{{ $t('Lock') }}</el-button>
              &emsp;
              <el-button type="primary" v-prevent-re-click @click="submitData">{{ $t('Save') }}</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-main>
    </el-container>
  </el-dialog>
</template>

<script>
export default {
  name: 'ScriptSetSetup',
  components: {
  },
  watch: {
    show(val) {
      if (val && this.$refs.form) {
        this.$refs.form.clearValidate();
      }
    },
  },
  methods: {
    async loadData(id) {
      if (!id) {
        this.pageMode = 'add';
        this.T.jsonClear(this.form);
        this.data = {};

      } else {
        this.pageMode = 'setup';
        this.data.id = id;

        let apiRes = await this.T.callAPI_getOne('/api/v1/script-sets/do/list', this.scriptSetId);
        if (!apiRes || !apiRes.ok) return;

        this.data = apiRes.data;

        let nextForm = {};
        Object.keys(this.form).forEach(f => nextForm[f] = this.data[f]);
        this.form = nextForm;
      }

      this.show = true;
    },
    async submitData() {
      try {
        await this.$refs.form.validate();
      } catch(err) {
        return console.error(err);
      }

      let dataId = null;
      switch(this.pageMode) {
        case 'add':
          dataId = await this.addData();
          break;

        case 'setup':
          dataId = await this.modifyData();
          break;
      }

      if (dataId) {
        this.$store.commit('updateEditor_selectedItemId', null);
      }
    },
    async addData() {
      let apiRes = await this.T.callAPI('post', '/api/v1/script-sets/do/add', {
        body    : { data: this.T.jsonCopy(this.form) },
        feedback: { okMessage: this.$t('Script Set created') },
      });
      if (!apiRes || !apiRes.ok) return;

      this.$store.commit('updateScriptListSyncTime');
      this.show = false;

      return apiRes.data.id;
    },
    async modifyData() {
      let _formData = this.T.jsonCopy(this.form);
      delete _formData.id;

      let apiRes = await this.T.callAPI('post', '/api/v1/script-sets/:id/do/modify', {
        params  : { id: this.scriptSetId },
        body    : { data: _formData },
        feedback: { okMessage: this.$t('Script Set saved') },
      });
      if (!apiRes || !apiRes.ok) return;

      this.$store.commit('updateScriptListSyncTime');
      this.show = false;

      return this.scriptSetId;
    },
    async deleteData() {
      if (!await this.T.confirm(this.$t('Are you sure you want to delete the Script Set?'))) return;

      let apiRes = await this.T.callAPI('/api/v1/script-sets/:id/do/delete', {
        params  : { id: this.scriptSetId },
        feedback: { okMessage: this.$t('Script Set deleted') },
      });
      if (!apiRes || !apiRes.ok) return;

      this.$store.commit('updateScriptListSyncTime');
      this.show = false;
    },

    showLockConfig() {
      this.$parent.$refs.ScriptSetLockConfig.loadData(this.scriptSetId);

      setTimeout(() => {
        this.show = false;
      }, 150);
    },
  },
  computed: {
    pageTitle() {
      const _map = {
        setup: this.$t('Setup Script Set'),
        add  : this.$t('Add Script Set'),
      };
      return _map[this.pageMode];
    },
    scriptSetId() {
      switch(this.pageMode) {
        case 'add':
          return this.form.id;
        case 'setup':
          return this.data.id;
      }
    },

    lockedByUserId() {
      return this.data.lockedByUserId;
    },
    lockedByUser() {
      return this.data.lockedByUserName || this.data.lockedByUsername;
    },
    isLockedByMe() {
      return this.lockedByUserId === this.$store.getters.userId;
    },
    isLockedByOther() {
      return this.lockedByUserId && !this.isLockedByMe;
    },
    canSetup() {
      return this.common.lockConfigCan(this.lockedByUserId, this.data.lockConfigMemberAllowMap, [ 'scriptSet_setup']);
    },

    requirementsLine() {
      if (!this.form.requirements) return null;

      let line = this.form.requirements.split(/\s+/).join(' ');
      return line;
    },
  },
  props: {
  },
  data() {
    return {
      show    : false,
      pageMode: null,

      data: {},
      form: {
        id          : null,
        title       : null,
        description : null,
        requirements: null,
      },
      formRules: {
        id: [
          {
            trigger : 'blur',
            message : this.$t('Please input ID'),
            required: true,
          },
          {
            trigger: 'change',
            message: this.$t('Only alphabets, numbers and underscore are allowed'),
            pattern: /^[a-zA-Z0-9_]*$/g,
          },
          {
            trigger: 'change',
            message: this.$t('Cannot not starts with a number'),
            pattern: /^[^0-9]/g,
          },
          {
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (value && value.indexOf('__') >= 0) {
                let _message = this.$t('ID cannot contains double underscore "__"');
                return callback(new Error(_message));
              }
              return callback();
            },
          },
        ],
      },
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
